//
//  SWAssetsManager.swift
//  ChildStory
//  事件照片管理器
//  Created by linhan on 2016/11/21.
//  Copyright © 2016年 Aiya. All rights reserved.
//

import Foundation

private let _manager:SWAssetsManager = SWAssetsManager()
class SWAssetsManager: NSObject
{
    private var _basePath:String = ""
    private var _dataPath:String = ""
    
    private var _launch:Bool = false
    private var _records:[SWAssetRecord] = []
    
    class func sharedManager() -> SWAssetsManager
    {
        return _manager
    }
    
    var assets:[SWAssetRecord]{
        return _records
    }
    
    override init() {
        
    }
    
    func launch()
    {
        if !_launch
        {
            _launch = true
            
            _basePath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).valueAt(0) ?? ""
            _dataPath = "\(_basePath)/assets.data"
            _records = SWCacheManager.sharedManager().readCache(_dataPath) as? [SWAssetRecord] ?? []
            _records.sort(by: {$0.addedTime > $1.addedTime})
        }
    }
    
    func fetchAsset(_ localID:String) -> SWAssetRecord?
    {
        if let index = _records.index(where: {($0.localID ?? "") == localID}),
           let record = _records.valueAt(index)
        {
            return record
        }
        return nil
    }
    
    //取出对应事件的照片，按收藏时间先后
    func fetchEventPhotoForBook(eventID:String) -> [SWAssetRecord]
    {
        let assets:[SWAssetRecord] = self.assets.filter({($0.eventID ?? "") == eventID && $0.valid})
        var favorites:[SWAssetRecord] = assets.filter({$0.isFavorite})
        var normals:[SWAssetRecord] = assets.filter({!$0.isFavorite})
        favorites.sort(by: {$0.favoriteTime > $1.favoriteTime})
        normals.sort(by: {$0.addedTime > $1.addedTime})
        var returnAssets:[SWAssetRecord] = []
        returnAssets += favorites
        returnAssets += normals
        return returnAssets
    }
    
    //新增
    @discardableResult
    func addAsset(localID:String, event:SWKidEvent?) -> SWAssetRecord?
    {
        return addAssets(localIDs: [localID], event: event).valueAt(0)
    }
    
    //新增
    @discardableResult
    func addAssets(localIDs:[String], event:SWKidEvent?) -> [SWAssetRecord]
    {
        var assets:[SWAssetRecord] = []
        for localID in localIDs
        {
            if let index = _records.index(where: {($0.localID ?? "") == localID}),
                let record = _records.valueAt(index)
            {
                if let event = event
                {
                    changeAsset(asset: record, event: event)
                }
                assets.append(record)
            }
            else
            {
                let record:SWAssetRecord = SWAssetRecord()
                record.localID = localID
                record.addedTime = Int(Date().timeIntervalSince1970)
                if let event = event
                {
                    changeAsset(asset: record, event: event)
                }
                _records.append(record)
                assets.append(record)
            }
        }
        save()
        //首页事件取最新添加照片,所以需要发送通知
        if let eventID = event?.eventID, eventID != "" && localIDs.count > 0
        {
            SWNotificationCenter.post(name: NotificationName.AssetClassified, object: nil, userInfo: [SWKey.eventID:eventID, "localIDs":localIDs], queue: nil)
        }
        return assets
    }
    
    //修改属性
    func changeAsset(localID:String, event:SWKidEvent)
    {
        if let record = fetchAsset(localID)
        {
            changeAsset(asset: record, event: event)
            save()
        }
        else
        {
            addAsset(localID: localID, event: event)
        }
        
        if let eventID = event.eventID, eventID != ""
        {
            SWNotificationCenter.post(name: NotificationName.AssetClassified, object: nil, userInfo: [SWKey.eventID:eventID, "localIDs":[localID]], queue: nil)
        }
    }
    
    func changeAsset(asset:SWAssetRecord, event:SWKidEvent)
    {
        asset.eventID = event.eventID
        asset.eventName = event.title
        asset.classifiedTime = Int(Date().timeIntervalSince1970)
        let assets:[SWAssetRecord] = self.assets.filter({($0.eventID ?? "") == (event.eventID ?? "")})
        if assets.count < SW.Config.MaxFavoritePhotoCount
        {
            asset.isFavorite = true
            asset.favoriteTime = Int(Date().timeIntervalSince1970)
        }
    }
    
    //修改属性(是否收藏)
    func changeAsset(localID:String, favorite:Bool)
    {
        if let record = fetchAsset(localID)
        {
            record.isFavorite = favorite
            record.favoriteTime = Int(Date().timeIntervalSince1970)
            save()
        }
    }
    
    //移除
    @discardableResult
    func removeAsset(localID:String) -> Bool
    {
        if let index = _records.index(where: {($0.localID ?? "") == localID}),
           let record = _records.valueAt(index)
        {
            record.isFavorite = false
            _records.removeAtIndexSafely(index)
            save()
            return true
        }
        return false
    }
    
    //图片编辑后无法在系统相册替代旧图片，只能新增一张，因此需要将记录指向到新的图片
    func replaceAsset(oldLocalID:String, newLocalID:String)
    {
        if let record = fetchAsset(oldLocalID)
        {
            record.localID = newLocalID
            record.classifiedTime = Int(Date().timeIntervalSince1970)
            save()
        }
    }
    
    private func save()
    {
        SWCacheManager.sharedManager().writeCache(_records, path: _dataPath)
    }

}
